﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
//
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Globalization;
//
/*
Copyright 2010 Mirosław M. Mączka

This file is part of Flac2Wma.

    Flac2Wma is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace Flac2Wma
{


    public class Utils
    {
        [DllImport("user32.dll")]
        extern public static bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
        //
        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        static readonly IntPtr HWND_TOP = new IntPtr(0);
        static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
        //
        private const UInt32 SWP_NOSIZE = 0x0001;
        private const UInt32 SWP_NOMOVE = 0x0002;
        private const UInt32 SWP_NOZORDER = 0x0004;
        private const UInt32 SWP_NOREDRAW = 0x0008;
        private const UInt32 SWP_NOACTIVATE = 0x0010;
        private const UInt32 SWP_FRAMECHANGED = 0x0020; /* The frame changed: send WM_NCCALCSIZE */
        private const UInt32 SWP_SHOWWINDOW = 0x0040;
        private const UInt32 SWP_HIDEWINDOW = 0x0080;
        private const UInt32 SWP_NOCOPYBITS = 0x0100;
        private const UInt32 SWP_NOOWNERZORDER = 0x0200; /* Don't do owner Z ordering */
        private const UInt32 SWP_NOSENDCHANGING = 0x0400; /* Don't send WM_WINDOWPOSCHANGING */        //
        //
        private static Regex rYear;
        //
        private static Regex rWYear;
        //
        static Utils()
        {
            rYear = new Regex(@"([12][0-9][0-9][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            rWYear = new Regex(@"^[12][0-9][0-9][0-9] (.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            //
        }

        public static void WindowToBackground(IntPtr hWnd)
        {
            SetWindowPos(hWnd,
               HWND_BOTTOM,
               0, 0, 0, 0,
               SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        }
        //
        public static bool WriteString(string pathName, string var)
        {
            FileStream fsOut = null;
            StreamWriter sw = null;
            try
            {
                fsOut = new FileStream(pathName, FileMode.Create, FileAccess.Write, FileShare.Read);
            }
            catch
            //catch (Exception e)
            {
                //
                return false;
            }
            sw = new StreamWriter(fsOut);
            sw.Write(var);
            sw.Close(); sw = null;
            fsOut.Close(); fsOut = null;
            //
            return true;
        }


        public static string FindExecutable(string executableName)
        {
            try
            {
                if (File.Exists(Path.Combine(Environment.CurrentDirectory, executableName)))
                {
                    return Path.Combine(Environment.CurrentDirectory, executableName);
                }
            }
            catch { }
            //
            try
            {
                if (File.Exists(Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), executableName)))
                {
                    return Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), executableName);
                }
            }
            catch { }
            //
            try
            {
                if (File.Exists(Path.Combine(Environment.SystemDirectory, executableName)))
                {
                    return Path.Combine(Environment.SystemDirectory, executableName);
                }
            }
            catch { }
            //
            
            //Environment.GetFolderPath
            //Environment.SpecialFolder
            foreach(string e in Environment.GetEnvironmentVariables().Values)
            {
                try
                {
                    if (File.Exists(Path.Combine(e, executableName)))
                    {
                        return Path.Combine(e, executableName);
                    }
                }
                catch { }
            }
            return "";
        }

        //--------------------------------------
        //--------------------------------------
        //--------------------------------------
        //--------------------------------------
        public static string GetYearFromString(string s)
        {
            Match mYear = rYear.Match(s);
            if (mYear.Success)
            {
                if (2 == mYear.Groups.Count)
                {
                    return mYear.Groups[1].Value;
                }
            }
            return "";
        }
        //--------------------------------------
        public static string GetWithoutYearFromString(string s)
        {
            Match mWYear = rWYear.Match(s);
            if (mWYear.Success)
            {
                if (2 == mWYear.Groups.Count)
                {
                    return mWYear.Groups[1].Value;
                }
            }
            return s;
        }
        //--------------------------------------
        public static string GetPathRegressed(string path)
        {
            string[] currentPathE = null;
            string tempPath = "";
            //
            try
            {
                //currentPathE = mc.myStartDirectory.Split(new Char[] { Path.AltDirectorySeparatorChar });
                currentPathE = path.Split('\\');
                //
                for (int n = currentPathE.GetLength(0) - 1; n >= 0; n--)
                {
                    
                    for (int k = 0; k <= n; k++)
                    {
                        //tempPath = tempPath + (0 == k ? @"" : @"\") + currentPathE[k];
                        if (0 == k)
                        {
                            tempPath = currentPathE[k];
                        }
                        else
                        {
                            tempPath = tempPath + @"\" + currentPathE[k];
                        }
                    }
                    if (Directory.Exists(tempPath))
                    {
                        return tempPath;
                    }
                }
            }
            catch
            {
                return "";
            }
            return "";
        }
        //--------------------------------------
        public static string ReplaceRegular(string source, string replacement, string regex)
        {
            Regex r;
            string dest;
            //
            try
            {
                r = new Regex(regex, RegexOptions.IgnoreCase);
                dest = r.Replace(source, replacement);
                return dest;
            }
            catch
            {
                return source;
            }

            //
            //
        }
        //--------------------------------------
        public static bool isNumberOnly(string s)
        {
            if (null == s) return false;
            //
            foreach (char c in s.Trim().ToCharArray())
            {
                if (Char.IsDigit(c)) continue;
                return false;
            }
            //
            return true;
        }
        //--------------------------------------
        public static string RemoveTrailingTildes(string s)
        {
            return s.TrimEnd().TrimEnd(new char[] { '~' }).TrimEnd();
        }
        //--------------------------------------
        public static bool Rename(string nameOld, string nameNew)
        {
            if (0 == String.Compare(nameOld, nameNew, false))//są takie same
            {
                return true;
            }
            //
            if (0 == String.Compare(nameOld, nameNew, true))//różnica tylko w case
            {
                //
                string tmpNewName = nameNew + "~";
                //
                if (File.Exists(tmpNewName)) tmpNewName += "~";
                if (File.Exists(tmpNewName)) tmpNewName += "~";
                if (File.Exists(tmpNewName)) tmpNewName += "~";
                if (File.Exists(tmpNewName))
                {
                    throw new FileNotFoundException();// to nie jest dobre
                    //return false;
                }
                //
                File.Move(nameOld, tmpNewName);
                File.Move(tmpNewName, nameNew);
                //
                return true;
            }
            //
            File.Move(nameOld, nameNew);
            //
            return true;
        }
        //--------------------------------------
        public static string CleanFileName(string s)
        {
            char[] invs = Path.GetInvalidFileNameChars();
            //
            s = s.Replace('<','«');
            s = s.Replace('>','»');
            //
            s = s.Replace('"', '\'');
            //
            foreach (char c in invs)
            {
                s = s.Replace(c, '_');
            }
            //
            s = RemoveAccents(s);
            s = RemoveQuotes(s);
            //
            return s;
        }
        //--------------------------------------
        public static string CleanDrop(string s)
        {
            s = RemoveQuotes(s.Trim());
            //
            return s;
        }
        //--------------------------------------
        public static string RemoveAccents(string s)
        {
            string so = "";
            //
            s = s.Normalize(NormalizationForm.FormD);

            for (int ich = 0; ich < s.Length; ich++)
            {
                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(s[ich]);
                if (uc != UnicodeCategory.NonSpacingMark)
                {
                    so += s[ich];
                }
            }
            //
            return so;
        }
        //--------------------------------------
        public static string RemoveQuotes(string s)
        {
            if(s.StartsWith("\"") && s.EndsWith("\""))
            {
                return s.Substring(1, s.Length - 2);
            }
            //
            return s;
        }
        //--------------------------------------
        public static string swapThe(string s)
        {
            //
            s = s.Trim();
            if (", The" == s) return s;
            //
            if(s.EndsWith(", The", StringComparison.InvariantCultureIgnoreCase))
            {
                if (!s.StartsWith("The ", StringComparison.InvariantCultureIgnoreCase))
                {
                    s = "The " + s.Substring(0, s.Length - ", The".Length);
                }
            }
            //
            return s;
        }
        //--------------------------------------
        public static bool isEmpty(string s)
        {
            if (null == s) return true;
            //
            if ("" == s.Trim()) return true;
            //
            return false;
        }
        //--------------------------------------
        public static bool isTrackNumberEmpty(string s)
        {
            if (null == s) return true;
            //
            s = s.Trim();
            if ("" == s) return true;
            //
            int i = 0;
            if(int.TryParse(s, out i))
            {
                return 0 == i;
            }
            //
            return false;
        }
        //--------------------------------------
        public static bool isDotsInsteadSpaces(string s)
        {
            if (null == s) return true;
            //
            int nSpaces = 0;
            int nDots =0;
            foreach (char c in s.ToCharArray())
            {
                if (' ' == c) nSpaces++;
                else if ('.' == c) nDots++;
            }
            //
            return (nDots > 1) && (0 == nSpaces);
        }
        //--------------------------------------
        public static bool areAllTracksEmpty(string [] ss)
        {
            int n = 0;
            foreach (string s in ss)
            {
                if (isTrackNumberEmpty(s)) n++;
            }
            return n == ss.Length;
        }
        //--------------------------------------
        /// <summary>
        /// sprawdza, czy podane w rablicy numery scieżek są poprawne
        /// - wszystkie są liczbami
        /// - są unikalne
        /// </summary>
        /// <param name="ss">tablica numerów ścieżek</param>
        /// <returns>true - gdy numery scieżek wyglądają na poprawne</returns>
        public static bool areAllTracksNumbers(string[] ss)
        {
            int n = 0;
            foreach (string s in ss)
            {
                if (isNumberOnly(s)) n++;
            }
            return n == countTrackNumbers(ss);
        }
        //--------------------------------------
        public static int countTrackNumbers(string[] ssTracks)
        {
            Hashtable ht = new Hashtable();
            foreach (string s in ssTracks)
            {
                if (null == s) continue;
                if (ht.ContainsKey(s)) continue;
                ht.Add(s, null);
            }
            return ht.Count;
        }
        //--------------------------------------
        public static int getMinLength(string[] ss, out int maxCommonLengthNo)
        {
            // wspolna częśc nie może być dłuższa os najkrótszego elementu
            int maxCommonLength = ss[0].Length;
            maxCommonLengthNo = 0;
            for (int k = 1; k < ss.Length; k++)
            {
                if (null == ss[k]) continue;
                if (ss[k].Length < maxCommonLength)
                {
                    maxCommonLength = ss[k].Length;
                    maxCommonLengthNo = k;
                }
            }
            return maxCommonLength;
        }
        //--------------------------------------
        public static string Number2Track(int n)
        {
            string fmt = "{0:00}";
            if (n > 99) fmt = "{0:000}";
            return string.Format(fmt, n);
        }
        //--------------------------------------
        public static string Number2Track(int n, int count)
        {
            int nDigits = (int)(Math.Log10(count) / Math.Log10(10)) + 1;
            if (nDigits < 2) nDigits = 2;
            //
            string fmt = "{0:" + "0".PadRight(nDigits, '0') + "}";
            return string.Format(fmt, n);
        }
        //--------------------------------------
        //--------------------------------------
        public static string CurrentTwoLetterLanguage()
        {
            return System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
        }
        //--------------------------------------
        public static void RenameHelpFiles()
        {
            try
            {
                string[] files = Directory.GetFiles(".", "help-??.mht.bin");
                foreach (string f in files)
                {
                    string newName = Path.GetFileNameWithoutExtension(f);
                    if (File.Exists(newName))
                    {
                        File.Delete(newName);
                    }
                    File.Move(f, Path.GetFileNameWithoutExtension(f));
                }
            }
            catch (Exception e)
            {
                ;
            }
        }
        //--------------------------------------
        //--------------------------------------



    }//class
}//namespace
